/*
 * RunTestDialog.java
 *
 * Created on Oct 11, 2010, 2:49:09 PM
 */
package ws.performancetest.app.gui.dialog;

import java.util.List;
import ws.performancetest.api.Test;
import ws.performancetest.app.gui.Application;
import ws.performancetest.api.TestSuite;
import ws.performancetest.app.gui.strings.AppStrings;

/**
 * Dialog for showing the test progress.
 * 
 * @author Wilson Santos, 36228 <wilson.santos@ua.pt>
 */
public class RunTestDialog extends javax.swing.JDialog {

  private String currentTestSuite;
  private Thread testRunnerThread;
  private final TestSuite testRunner;
  private List<Test> selectedTestList;
  private float testCount = 0;
  private float testCountTotal;

  public RunTestDialog(TestSuite testSuite, List<Test> selectedTestList) {
    super(new javax.swing.JFrame(), true);

    initComponents();
    addWindowListener(new java.awt.event.WindowAdapter() {

      @Override
      public void windowClosing(java.awt.event.WindowEvent e) {
        dispose();
      }
    });

    this.currentTestSuite = testSuite.toString();
    this.testCountTotal = testSuite.getThreadCount() * testSuite.getSamplesCount() * selectedTestList.size() * testSuite.getCycleCount();
    this.selectedTestList = selectedTestList;
    testRunner = testSuite;
  }

  /**
   * Runs the test group.
   * 
   * @throws InterruptedException
   */
  public void run() throws InterruptedException {
    lbCurrentTestSuite.setText("Running '" + currentTestSuite + "', please wait...");

    /* Show frame. */
    java.awt.EventQueue.invokeLater(new Runnable() {

      public void run() {
        setVisible(true);
      }
    });

    /* Start a thread to show the progress. */
    new Thread(new Runnable() {

      public void run() {
        synchronized (testRunner) {
          try {
            while (testCount < testCountTotal) {
              testRunner.wait();
              testCount++;
              int progress = (int) (testCount / testCountTotal * 100);
              jProgressBar1.setValue(progress);
            }
          } catch (InterruptedException ex) {
            dispose();
            ex.printStackTrace();
            ErrorDialog.run(AppStrings.createExceptionMessage(ex));
          }
        }
      }
    }).start();

    /* Start a thread to run the test suite. */
    testRunnerThread = new Thread(new Runnable() {

      public void run() {
        try {
          testRunner.runSelectedTests(selectedTestList);
          lbCurrentTestSuite.setText("'" + currentTestSuite + "' finished!");
          btCancel.setText("Close");

          Application.setOKLabel("Test group '" + currentTestSuite + "' finished!");
        } catch (Exception ex) {
          dispose();
          ex.printStackTrace();
          ErrorDialog.run(AppStrings.createExceptionMessage(ex));
        }
      }
    });
    testRunnerThread.setPriority(Thread.MAX_PRIORITY);
    testRunnerThread.start();
  }

  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    lbCurrentTestSuite = new javax.swing.JLabel();
    btCancel = new javax.swing.JButton();
    jProgressBar1 = new javax.swing.JProgressBar();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Run Test Group");

    lbCurrentTestSuite.setFont(new java.awt.Font("Droid Sans", 1, 12)); // NOI18N
    lbCurrentTestSuite.setText("jLabel1");

    btCancel.setText("Cancel");
    btCancel.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        btCancelActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)
          .addGroup(layout.createSequentialGroup()
            .addComponent(lbCurrentTestSuite)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 274, Short.MAX_VALUE)
            .addComponent(btCancel)))
        .addContainerGap())
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(lbCurrentTestSuite)
          .addComponent(btCancel))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void btCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelActionPerformed
    if (testRunnerThread.isAlive()) {
      /* Cancel current test group. */
      testRunnerThread.interrupt();
      testRunner.interrupt();
    }
    dispose();
  }//GEN-LAST:event_btCancelActionPerformed
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton btCancel;
  private javax.swing.JProgressBar jProgressBar1;
  private javax.swing.JLabel lbCurrentTestSuite;
  // End of variables declaration//GEN-END:variables
}
